<?php

class verifyLogin extends CI_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('login_model', 'login', TRUE);
	}

	function index() {
		$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

		if ($this->form_validation->run() == FALSE) {
			$this->load->view('login');
		}
		else {
			$login = $this->input->post('login');
			if ($login == 'admin') {
				redirect('admin_home', 'refresh');
			}
			else {
			redirect('home', 'refresh');
			}
		}
	}

	function check_database($password) {
		$login = $this->input->post('login');
		$result = $this->login->login($login, $password);
		if ($result) {
			$sess_array = array();
			foreach($result as $row) {
				$sess_array = array('id' => $row->id,
									'login' => $row->login,
									'first' => $row->first,
									'last' => $row->last,
									'email' => $row->email
									);
				$this->session->set_userdata('logged_in', $sess_array);
			}
		return TRUE;
		}
		else {
			$this->form_validation->set_message('check_database', 'Invalid login/password');
			return FALSE;
		}
	}
}
